package com.usian.skill.mq;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.GoodsService;
import com.usian.skill.service.SkillOrderService;
import com.usian.skill.service.SkillService;
import com.usian.skill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqReceiver {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SkillOrderService skillOrderService;

    @Autowired
    private SkillService skillService;

    @RabbitListener(queues = MqConfig.QUEUE)
    public void receive(String message){
        log.info("receive message:"+message);
    }

    @RabbitListener(queues = MqConfig.SKillQUEUE)
    public void receiveSkill(String message){
        SkillMsgAge skillMsgAge= JSON.parseObject(message,SkillMsgAge.class);
        GoodsVo goodsVo=goodsService.getgoodsvobyidDB(skillMsgAge.getGoodsId());
        if (goodsVo.getStockCount()<=0){
            return;
        }
//        判断是否秒杀到了

        SkillOrder order=skillOrderService.getOne(Wrappers.<SkillOrder>lambdaQuery().eq(SkillOrder::getOrderId,skillMsgAge.getGoodsId()).eq(SkillOrder::getUserId,skillMsgAge.getUserId()));
        if (order!=null){
            return;
        }
//        减去库存 添加订单
        skillService.deleteKuCunAndAddDingDan(skillMsgAge.getUserId().toString(),goodsVo);

        log.info("receive message:"+message);
    }
}
